package sk.naive.talker.command;

import sk.naive.talker.*;
import sk.naive.talker.persistence.*;
import sk.naive.talker.message.DefaultMessageFactory;

import java.rmi.RemoteException;
import java.util.*;

/**
 * @author <a href="mailto:rytier@naive.deepblue.sk">Martin "Rytier" Kerni</a>
 * @version $Revision: 1.9 $ $Date: 2005/02/22 20:21:06 $
 */
public class Boards extends AbstractCommand {
	public void exec()
		throws CommandException,
		RemoteException
	{
		try {
			TextPersistence tp = commandDispatcher.textPersistence();
			BoardFinder bf = commandDispatcher.boardFinder();

			if (bf.boards().size() == 0) {
				user.send(getString("boards.notDefined", user.getProperties(), user.getLang()));
				return;
			} else {
				StringBuilder sb = new StringBuilder();
				sb.append(getString("boards.head", user.getProperties(), user.getLang()));
				Set boards = new TreeSet(new Comparator() {
					public int compare(Object o1, Object o2) {
						return ((Board) o1).getName().compareTo(((Board) o2).getName());
					}
				});
				boards.addAll(bf.boards());
				for (Iterator i = boards.iterator(); i.hasNext();) {
					Board brd = (Board) i.next();
					int text_size = brd.texts().size();
					user.getProperties().put(DefaultMessageFactory.CTXKEY_VAL, brd.getName());
					if (text_size > 0) {
						user.getProperties().put(DefaultMessageFactory.CTXKEY_VAL + 1, String.valueOf(text_size));
						user.getProperties().put(DefaultMessageFactory.CTXKEY_VAL + 2, brd.texts().get(0).getCreated(tp));
						sb.append(getString("boards.line", user.getProperties()));
					} else {
						sb.append(getString("boards.none", user.getProperties()));
					}
				}
				sb.append(getString("boards.tail", user.getProperties(), user.getLang()));
				user.send(sb.toString());
			}
		} catch (PersistenceException e) {
			throw new CommandException(e);
		}
	}
}

